package com.huayun.code.core.utils;

import com.huayun.code.core.config.CodeGenConfig;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class NameUtils {

    private static CodeGenConfig config;

    @Autowired
    public void setConfig(CodeGenConfig config) {
        NameUtils.config = config;
    }

    public static String getFieldName(String columnName) {
        String[] words = toLowerCaseArray(columnName);
        StringBuilder field = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            if (i == 0) {
                field.append(words[i]);
            } else {
                field.append(StringUtils.capitalize(words[i]));
            }
        }
        return field.toString();
    }

    public static String getCapitalizeFieldName(String fieldName) {
        return StringUtils.capitalize(fieldName);
    }

    public static String getter(String columnName) {
        return capitalizeWords("get", columnName);
    }

    public static String setter(String columnName) {
        return capitalizeWords("set", columnName);
    }

    public static String getModelName(String tableName) {
        String[] tableNames = StringUtils.split(config.getTable(), ',');
        int index = ArrayUtils.indexOf(tableNames, tableName);
        String value = StringUtils.split(config.getModel(), ',')[index];
        return value == null ? capitalizeWords("", tableName) : value;
    }

    public static String getRequestMapping(String tableName) {
        String[] tableNames = StringUtils.split(config.getTable(), ',');
        int index = ArrayUtils.indexOf(tableNames, tableName);
        String value = StringUtils.split(config.getRequestMapping(), ',')[index];
        return value == null ? "" : value;
    }

    public static String getBeanName(String tableName) {
        String clazzName = getModelName(tableName);
        return StringUtils.uncapitalize(clazzName);
    }

    private static String capitalizeWords(String prefix, String columnName) {
        String[] words = toLowerCaseArray(columnName);
        StringBuilder field = new StringBuilder(prefix);
        for (int i = 0; i < words.length; i++) {
            field.append(StringUtils.capitalize(words[i]));
        }
        return field.toString();
    }

    private static String[] toLowerCaseArray(String columnName) {
        String[] words = StringUtils.split(columnName, "_");
        for (int i = 0; i < words.length; i++) {
            words[i] = words[i].toLowerCase();
        }
        return words;
    }

}
